//
//  TWChoicenessViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/9.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SDWebImage
import SDCycleScrollView
import SVProgressHUD

let FromChoicenessVc = "TWChoicenessViewController"


class TWChoicenessViewController: UIViewController {

    // MARK:- 懒加载
    fileprivate lazy var tableView : UITableView = UITableView()                            // 表视图
    fileprivate lazy var headerView : TWHeaderView = TWHeaderView()                         // 自定义的头部视图
    fileprivate lazy var footerView : TWFooterView = TWFooterView.createFooterView()        // 脚部视图
    fileprivate lazy var footerNullView : UILabel = UILabel()                               // 空的脚部视图
    fileprivate lazy var barBackgroundView : UIView = UIView()                              // 电池栏的背景层
    fileprivate lazy var itemsArray : NSMutableArray = NSMutableArray()                     // 存放数据的字典数组
    fileprivate lazy var nextPageUrl : String = String()                                    // 下一页网址
    fileprivate lazy var nextPublishTime : NSNumber = NSNumber()                            // 下次发布时间
    fileprivate lazy var searchViewAnimator : TWSearchAnimator = TWSearchAnimator()
//    fileprivate lazy var animationView : TWAnimationView = TWAnimationView.createAnimationView()
//    fileprivate lazy var animationViewController : TWAnimationViewController = TWAnimationViewController()
    fileprivate lazy var animationTool : TWAnimationTool = TWAnimationTool()
    
    
    // 添加在tableView上的
    fileprivate lazy var tapButton : UIButton = UIButton()                                  // 加在tableView最顶上的按钮，用来响应头部视图的点击事件
    fileprivate lazy var activityIndicatorView = UIActivityIndicatorView()                  // 刷新
    fileprivate lazy var searchButton : UIButton = UIButton()                               // 响应搜索响应的按钮
    
    // MARK:- 属性
    var showLightBarStyle :Bool = true                                                      // 切换状态栏的颜色
    var isHeaderRefreshing :Bool = false                                                    // 正在下拉刷新
    var isFooterRefreshing :Bool = false                                                    // 正在上拉加载更多
    var isloadNewData :Bool = false                                                         // 加载最新数据
    
    /// 修改状态栏的颜色
    override var preferredStatusBarStyle: UIStatusBarStyle{
        if showLightBarStyle {
            return .lightContent
        } else {
            return .`default`
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 在页面出现的时候就将导航隐藏起来
        navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 在页面消失的时候就让navigationbar还原
        navigationController?.navigationBar.isHidden = false
        SVProgressHUD.dismiss()
    }
    // MARK:- 系统回调函数
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        SVProgressHUD.dismiss()
//    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupHeaderView()
        setupTableView()
        setupFooterView()
        headereBeginRefresh()
        setupBarBackgroundView()
        setupNotifications()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- 通知
extension TWChoicenessViewController {
    fileprivate func setupNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(choicenessViewControllerTabBarButtonDidRepeatClick), name: NSNotification.Name(rawValue: TabBarButtonDidRepeatClickNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(detailCollectionViewCellDidClick(note:)), name: NSNotification.Name(rawValue: DetailCollectionViewCellDidClickNotification), object: nil)
    }
}


// MARK:- ——————————————搭建UI界面————————————————
extension TWChoicenessViewController {
    /// 添加头部视图
    fileprivate func setupHeaderView(){
        headerView = TWHeaderView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: CustemHeaderViewHeight))
        headerView.backgroundColor = UIColor.clear
        view.addSubview(headerView)
    }
    
    /// 添加脚部视图
    fileprivate func setupFooterView(){
        // 刷新时的tableFooterView
        footerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: TabBarHeight)
        footerView.addRotationAnimation()
        tableView.tableFooterView = footerView
        
        // 没有数据时的tableFooterView
        footerNullView = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        footerNullView.text = "-end-"
        footerNullView.font = UIFont.init(name: "Lobster1.4", size: 15)
        footerNullView.textAlignment = .center
    }
    
    /// 添加表视图
    fileprivate func setupTableView(){
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), style: .plain)
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.clear
        tableView.dataSource = self
        tableView.delegate = self
        tableView.scrollsToTop = false         // 暂时先禁掉
     
        // 注册
        tableView.register(UINib(nibName: "TWChoicenessItemCell", bundle: nil), forCellReuseIdentifier: VideoCell)
        tableView.register(UINib(nibName: "TWBannerCell", bundle: nil), forCellReuseIdentifier: BannerCell)
        tableView.register(UINib(nibName: "TWFooterCell", bundle: nil), forCellReuseIdentifier: FooterCell)
        tableView.register(UINib(nibName: "TWHeaderCell", bundle: nil), forCellReuseIdentifier: HeaderCell)
        tableView.register(UINib(nibName: "TWItemCollectionCell", bundle: nil), forCellReuseIdentifier: ItemCollectionCell)
        tableView.register(UINib(nibName: "TWHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: HorizontalScrollCardCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfFollowCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfFollowCell)
        tableView.register(UINib(nibName: "TWSquareCardCollectionCell", bundle: nil), forCellReuseIdentifier: SquareCardTableViewCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfAuthorWithCoverCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfAuthorWithCoverCell)
        
        
        // 设置内边距
        tableView.contentInset = UIEdgeInsets(top: CustemHeaderViewHeight, left: 0, bottom: TabBarHeight, right: 0)
        view.addSubview(tableView)
        setupClickView()
    }
    
    /// 添加响应点击事件的视图
    fileprivate func setupClickView(){
        // 点击事件的按钮
        tapButton = UIButton(type: .custom)
        tapButton.backgroundColor = UIColor.clear
        //【按钮的位置只需要固定住，不需要随着滚动而变化。因为点击操作只有等滚动结束才有可能被触发，也就是说需要响应点击操作的只有tableView的内嵌的那个高度的范围】
        tapButton.frame = CGRect(x: 0, y: -CustemHeaderViewHeight, width: UIScreen.main.bounds.width, height: CustemHeaderViewHeight)
        tapButton.addTarget(self, action: #selector(headerImageViewDidCilck), for: .touchUpInside)
        tableView.addSubview(tapButton)
        
        // 在时间按钮上再加上一个位置等同下层视图搜索按钮的搜索按钮
        searchButton = UIButton(type: .custom)
        searchButton.setImage(UIImage(named: "bar_ic_search_white_44x44_"), for: .normal)
        searchButton.frame = CGRect(x: UIScreen.main.bounds.width - 44, y: 20, width: 44, height: 44)
        searchButton.addTarget(self, action: #selector(searchButtomDidCilck), for: .touchUpInside)
        view.addSubview(searchButton)
    }
    
    /// 添加电池栏的背景视图
    fileprivate func setupBarBackgroundView(){
        barBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: BatteryHeight))
        barBackgroundView.backgroundColor = UIColor(red: 249/256.0, green: 249/256.0, blue: 249/256.0, alpha: 0.95)
        barBackgroundView.isHidden = true
        view.addSubview(barBackgroundView)
    }
}

// MARK:- ——————————————数据处理————————————————
extension TWChoicenessViewController {

    /// 请求最新网络数据
    fileprivate func loadNewData(urlString : String){
        loadingData(isLoadNewData: true, isLoadMoreData: false, urlString: ChoicenessUrlString)
    }
    /// 加载更多数据
    fileprivate func loadMoreData(){
        loadingData(isLoadNewData: false,isLoadMoreData: true,  urlString: nextPageUrl)
    }
    private func loadingData(isLoadNewData : Bool, isLoadMoreData: Bool, urlString : String){
        
        TWChoicenessCacheTool.shareInstence.loadChoicenessData(isLoadNewData: isLoadNewData, isLoadMoreData: isLoadMoreData, urlString: urlString) { (result, error) in
        
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败！")
                self.headereEndRefresh()
                self.footerEndRefresh()
                TWLog(message: error)
                return
            }
            guard let result = result else {
                return
            }
            
            let next = result["nextPageUrl"]
            if String(describing: next!) == "<null>" {
                self.tableView.tableFooterView = self.footerNullView
                self.footerEndRefresh()
                return
            } else {
                self.nextPageUrl = next as! String
            }
            self.nextPublishTime = result["nextPublishTime"] as! NSNumber
            
            // 处理cell相关的数据
            self.dealWithData(isLoadNewData : isLoadNewData, result: result)
        }
    }
    /// 对主体数据进行处理
    private func dealWithData(isLoadNewData : Bool, result : [String : AnyObject]){
        // 需要展示主体数据的数组
        let itemListArray = result["itemList"] as! [[String : AnyObject]]
        
        let tempArray : NSMutableArray = NSMutableArray()

        // 遍历数组,判断是什么类型
        for item in itemListArray {
            let dataType = item["type"] as! String
            // dataType一共有10种类型,根据类型不同分别转成不同的模型
            switch dataType {
            case video:
                let itemModel : TWItemModel = TWItemModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([video : itemModel])
            case textFooter:
                let itemModel : TWTextFooterModel = TWTextFooterModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textFooter : itemModel])
            case textHeader:
                let itemModel : TWTextHeaderModel = TWTextHeaderModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textHeader : itemModel])
            case videoCollectionWithCover:
                let itemModel : TWItemCollectionModel = TWItemCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionWithCover : itemModel])
            case videoCollectionOfFollow:
                let itemModel : TWVideoCollectionOfFollowModel = TWVideoCollectionOfFollowModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfFollow : itemModel])
            case squareCardCollection:
                let itemModel : TWSquareCardCollectionModel = TWSquareCardCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([squareCardCollection : itemModel])
            case videoCollectionOfAuthorWithCover:
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfAuthorWithCover : itemModel])
            case banner:
                let itemModel : TWBannerModel = TWBannerModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([banner : itemModel])
            case horizontalScrollCard:
                let itemModel : TWHorizontalScrollCard = TWHorizontalScrollCard(dict: item["data"] as! [String : AnyObject])
                tempArray.add([horizontalScrollCard : itemModel])
            default:
                TWLog(message: "这是一组未知类型的数据")
            }
        }
        
        if isLoadNewData {
            itemsArray.removeAllObjects()
            for item in tempArray {
                itemsArray.add(item)
            }
        } else {
            for item in tempArray {
                itemsArray.add(item)
            }
        }
        // 刷新UI
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.tableView.reloadData()
            self.tableView.tableFooterView = self.footerView
            self.headereEndRefresh()
            self.footerEndRefresh()
            SVProgressHUD.dismiss()
        }
    }
}


// MARK:- ——————————————监听事件点击————————————————
extension TWChoicenessViewController {
    @objc fileprivate func choicenessViewControllerTabBarButtonDidRepeatClick(){
        // 返回上去headerView有可能不显示，所有+1
        tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: -tableView.contentInset.top + 1), animated: true)
        headerView.isHidden = false
    }
    @objc fileprivate func headerImageViewDidCilck(){
        let everyDay : TWEveryDayViewController = TWEveryDayViewController()
        navigationController?.pushViewController(everyDay, animated: true)
    }
    
    @objc fileprivate func searchButtomDidCilck(){
        let searchVc : TWSearchViewController = TWSearchViewController()
        searchVc.modalPresentationStyle = .custom
        searchVc.transitioningDelegate = searchViewAnimator
        present(searchVc, animated: true, completion: nil)
    }
    @objc fileprivate func detailCollectionViewCellDidClick(note : NSNotification){
        
        let dict = note.object as! [String : AnyObject]
        if dict.keys.first == FromChoicenessVc {
            let selectModel = dict.values.first as! TWItemModel // 拿到当前选中的模型
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.itemModel = selectModel
            present(animationViewController, animated: true, completion: nil)
        }
     }
    // 手势
//    @objc fileprivate func handleUpSwipeFrom(){
//        animationView.halfBottom_ShowMoreButtonClick()
//    }
//    @objc fileprivate func handleDownSwipeFrom(){
//        animationView.hiddenAnimationView()
//    }
}


// MARK:- ——————————————代理方法————————————————
// MARK:- UITableViewDataSource代理方法
extension TWChoicenessViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 取出当前对应的类型
        let data = itemsArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        switch key {
        case video:
            return VideoCellHeight
        case textFooter:
            return headerFooterCellHeight
        case textHeader:
            return headerFooterCellHeight
        case videoCollectionWithCover:
            return VideoCollectionCellHeight
        case videoCollectionOfFollow:
            return VideoCollectionCellHeight
        case squareCardCollection:
            return squareCardCellHeight
        case videoCollectionOfAuthorWithCover:
            return VideoCollectionCellHeight
        case banner:
            return VideoCellHeight
        case horizontalScrollCard:
            return VideoCellHeight
        default:
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.tableFooterView?.isHidden = itemsArray.count == 0 ? true : false
        return itemsArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 取出当前对应的类型
        let data = itemsArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        switch key {
        case video:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCell, for: indexPath) as! TWChoicenessItemCell
            cell.selectionStyle = .none
            let itemModel = data.values.first as! TWItemModel
            cell.itemModel = itemModel
            return cell
        case textFooter:
            let cell = tableView.dequeueReusableCell(withIdentifier: FooterCell, for: indexPath) as! TWFooterCell
            cell.selectionStyle = .none
            let textFooter = data.values.first as! TWTextFooterModel
            cell.textFooter = textFooter
            return cell
        case textHeader:
            let cell = tableView.dequeueReusableCell(withIdentifier: HeaderCell, for: indexPath) as! TWHeaderCell
            cell.selectionStyle = .none
            let textHeader = data.values.first as! TWTextHeaderModel
            cell.textHeader = textHeader
            return cell
        case videoCollectionWithCover:
            // MARK:- 一下
            let cell = tableView.dequeueReusableCell(withIdentifier: ItemCollectionCell, for: indexPath) as! TWItemCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWItemCollectionModel
            cell.itemCollectionModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromChoicenessVc
            return cell
        case videoCollectionOfFollow:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfFollowCell, for: indexPath) as! TWVideoCollectionOfFollowCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfFollowModel
            cell.videoCollectionOfFollowModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromChoicenessVc
            return cell
        case squareCardCollection:
            let cell = tableView.dequeueReusableCell(withIdentifier: SquareCardTableViewCell, for: indexPath) as! TWSquareCardCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWSquareCardCollectionModel
            cell.squareCardCollectionModel = itemCollectionModel
            return cell
        case videoCollectionOfAuthorWithCover:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfAuthorWithCoverCell, for: indexPath) as! TWVideoCollectionOfAuthorWithCoverCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.VideoCollectionOfAuthorWithCoverModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromChoicenessVc
            return cell
        case banner:
            let cell = tableView.dequeueReusableCell(withIdentifier: BannerCell, for: indexPath) as! TWBannerCell
            cell.selectionStyle = .none
            let bannerModel = data.values.first as! TWBannerModel
            cell.bannerModel = bannerModel
            return cell
        case horizontalScrollCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: HorizontalScrollCardCell, for: indexPath) as! TWHorizontalScrollCardCell
            cell.selectionStyle = .none
            let horizontalScrollCardCellModel = data.values.first as! TWHorizontalScrollCard
            cell.horizontalScrollCardModel = horizontalScrollCardCellModel
            cell.horizontalScrollCardCellDelegate = self
            return cell
        default:
            return UITableViewCell()
        }
    }
}


// MARK:- UITableViewDelegate代理方法
extension TWChoicenessViewController : UITableViewDelegate {
    /// 添加每当VideoCell出现时的动画————没有缓存过的图片才有动画效果
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // 取出当前对应的类型
        let data = itemsArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 只有当cell是VideoCell时才出现
        if key == video {
            let model = data[video] as! TWItemModel
            let urlStr = model.cover?.detail
            // 异步检查图片是否已经被缓存
            let image = SDImageCache.shared().imageFromMemoryCache(forKey: urlStr)
            if image == nil {
                // 没有缓存就实行动画效果
                var rotation = CATransform3D()
                rotation = CATransform3DMakeTranslation(0, 50, 20)
                rotation = CATransform3DScale(rotation, 0.9, 0.9, 1.0)
                rotation.m34 = -1.0 / 600;
                cell.layer.shadowColor = UIColor.black.cgColor
                cell.layer.shadowOffset = CGSize(width: 10, height: 10)
                cell.alpha = 0;
                cell.layer.transform = rotation
                // 开始动画
                UIView.animate(withDuration: 0.5, animations: {
                    cell.layer.transform = CATransform3DIdentity// 获取一个标准默认的CATransform3D仿射变换矩阵
                    cell.alpha = 1
                    cell.layer.shadowOffset = CGSize(width: 0, height: 0)
                })
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 取出当前对应的类型
        let data = itemsArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        if key == video {
            let itemModel = data.values.first as! TWItemModel
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.modalPresentationStyle = .custom
            animationViewController.itemModel = itemModel
            animationViewController.transitioningDelegate = animationTool
            animationTool.presentedDelegate = self
            animationTool.dismissDelegate = self
            animationTool.indexPath = indexPath
            present(animationViewController, animated: true, completion: nil)
            
        } else if key == textFooter {
            let itemModel = data.values.first as! TWTextFooterModel
            TWLog(message: itemModel.text)
        }
    }
}

// MARK:- AnimationToolPresentDelegate代理方法
extension TWChoicenessViewController : AnimationToolPresentDelegate {
    func startRect(indexPath: IndexPath) -> CGRect {
        // 获取当前点击的cell
        let cell = tableView.cellForRow(at: indexPath) as! TWChoicenessItemCell
        // 获得开始时的frame
        let stratRect = tableView.convert(cell.frame, to: UIApplication.shared.keyWindow)
        return stratRect
    }
    func imageView(indexPath: IndexPath) -> UIImageView {
        let imageView = UIImageView()
        // 获取当前点击的model
        let data = itemsArray[indexPath.row] as! [String : AnyObject]
        let itemModel = data.values.first as! TWItemModel
        let picURL = itemModel.cover?.detail
        if let picURL = picURL {
            let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picURL)
            imageView.image = image
        } else {
            imageView.sd_setImage(with: URL(string: picURL!))
        }
        return imageView
    }
}

// MARK:- AnimationToolDismissDelegate代理方法
extension TWChoicenessViewController : AnimationToolDismissDelegate {
    func dismissImageView(indexPath: IndexPath) -> UIImageView {
        return imageView(indexPath: indexPath)
    }
}


// MARK:- UIScrollViewDelegate代理方法
extension TWChoicenessViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 拿到tableView的内边距top
        let insetTop = scrollView.contentInset.top
        // 滚动偏移量
        let offset : CGFloat = scrollView.contentOffset.y
        
        // 蒙版的透明度值
        let dismissValue = (offset + tableView.contentInset.top) / CustemHeaderViewHeight
        headerView.coverHeaderView(alpha: dismissValue)

        if offset <= -insetTop {
            downScroll(offset: offset, insetTop: insetTop)
        } else {
            upScroll(offset: offset)
        }
        // 滚动cell里面的视图
    }
    
    // 用户松开scrollView时调用
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // 滚动偏移量
        let offset : CGFloat = scrollView.contentOffset.y
        // 向下拉的值
        let scrollDownOffset = -(offset + tableView.contentInset.top)
        // 一旦拉到40px，开始刷新
        if scrollDownOffset > refreshingOffset {
           headereBeginRefresh()
        }
    }
    // 滚动停止后
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        headereEndRefresh()
    }
}

// MARK:- HorizontalScrollCardCellDelegate代理方法
extension TWChoicenessViewController : HorizontalScrollCardCellDelegate {
    func cycleScrollViewDidSelectItemAt(selectedItem: TWBannerModel) {
        TWLog(message: selectedItem.title)
    }
}


// MARK:- ——————————————自定义方法————————————————
extension TWChoicenessViewController {
    /// 向下滚动时要改变的子控件的frame
    fileprivate func downScroll(offset : CGFloat, insetTop : CGFloat){
        // 向下滚动
        var frame = headerView.frame
        frame.size.height = CustemHeaderViewHeight - (offset + insetTop)
        headerView.frame = frame
        headerView.headerImageView.frame = frame
        headerView.blackView.frame = frame
        
        if isHeaderRefreshing {
            return
        }
        // 计算向下拉的值
        let scrollDownOffset = -(offset + insetTop)
        if scrollDownOffset >= 0 {
            // 显示响应点击的searchButton
            searchButton.isHidden = false
        }
        // 准备刷新
        headerView.prepareForBeginRefresh(offset: scrollDownOffset)
    }
    /// 开始刷新
    fileprivate func headereBeginRefresh(){
        if isHeaderRefreshing {
            return
        }
        headerView.refreshing()
        isHeaderRefreshing = true
        // 请求数据
        loadNewData(urlString: ChoicenessUrlString)
    }
    /// 结束刷新
    fileprivate func headereEndRefresh(){
        headerView.endRefresh()
        isHeaderRefreshing = false
    }
    
    /// 向上滚动时要做的事情
    fileprivate func upScroll(offset : CGFloat){
        // 隐藏响应点击的searchButton
        searchButton.isHidden = true
        // 当向上滚动到贴上电池栏时 改变电池栏的状态
        if offset > -BatteryHeight {
            // 电池栏变成黑色
            showLightBarStyle = false
            // 通知系统去调用当前UIViewController的preferredStatusBarStyle方法在下次页面刷新时，调用重绘该view
            setNeedsStatusBarAppearanceUpdate()
            // 电池栏背景变成白色
            barBackgroundView.isHidden = false
            //
            headerView.isHidden = true
        } else {
            showLightBarStyle = true
            setNeedsStatusBarAppearanceUpdate()
            barBackgroundView.isHidden = true
            headerView.isHidden = false
        }
        // 计算偏移量 = 内容的顶部和frame的顶部的差值
        // tableView.contentSize包括header和footer
        let ofsetY = tableView.contentSize.height + tableView.contentInset.bottom - tableView.frame.height
        if offset >= ofsetY {
            footerBeginRefresh()
        }
    }
    /// 开始加载更多
    fileprivate func footerBeginRefresh(){
        if isFooterRefreshing {
            return
        }
        // 进入刷新状态
        isFooterRefreshing = true
        // 发送网络请求
        loadMoreData()
    }
    /// 结束加载更多
    fileprivate func footerEndRefresh(){
        isFooterRefreshing = false
    }
}

